import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
import { Toast } from 'antd-mobile'
import {
  UserOutline,
  UnlockOutline
} from 'antd-mobile-icons'
import "./Login.css"

axios.defaults.baseURL = "http://127.0.0.1:3000"


export default function Login() {

  const navigate = useNavigate()
  const [username, setusername] = useState('')
  const [password, setpassword] = useState('')

  const handleLogin = async () => {
    let obj = {
      username: username,
      password: password
    }
    let { data } = await axios.post("/login", {
      ...obj
    })
    if (data.code === 200) {
      console.log(data);
      sessionStorage.setItem('accesstoken', data.accessToken) //短token
      sessionStorage.setItem('refreshtoken', data.refreshToken) //长token
      sessionStorage.setItem('username', data.user.username)  //用户名
      sessionStorage.setItem('password', data.user.password) //密码
      navigate("/")
      Toast.show({
        content: '登录成功',
        // afterClose: () => {
        //   console.log('after');
        // },
      })
    }else{
      Toast.show({
        content: '登录失败',
        // afterClose: () => {
        //   console.log('after');
        // },
      })
    }
  }

  return (
    <div className='login'>
      <div className='lbox'>
        <p className='lbox-title'>登录</p>
        <div className='lbox-content'>
          <p className='ppp'>
            <span className='icon'><UserOutline /></span>
            <input type="text" placeholder='用户名' className='inputcss'
              value={username} onChange={(e) => { setusername(e.target.value) }} />
          </p>
          <p className='ppp'>
            <span className='icon'><UnlockOutline /></span>
            <input type="password" placeholder='密码' className='inputcss'
              value={password} onChange={(e) => { setpassword(e.target.value) }}
            />
          </p>
        </div>
        <button className='login-btn' onClick={handleLogin}>登录</button>
        <div className='login-bottom'>
          <span>注册</span>
          <span>忘记密码?</span>
        </div>
      </div>
    </div>
  )
}
